import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class testStudent {
    public static void create() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class c = Class.forName("Student");
        Student s = (Student) c.newInstance();
        System.out.println("创建学生对象: "+s);
    }

    public static void reflectConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class c = Class.forName("Student");
        Constructor<?> constructor = c.getConstructor();
        Student s = (Student) constructor.newInstance();
    }

    public static void reflectPrivateConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class c = Class.forName("Student");
        Constructor<?> constructor =  c.getDeclaredConstructor(String.class,int.class);
        constructor.setAccessible(true);
        Student s = (Student) constructor.newInstance("张三",2);
        System.out.println("私有方法构造的学生: "+s);
    }

    public static void reflectPrivateField() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class c = Class.forName("Student");
        Field f = c.getDeclaredField("classNumber");
        f.setAccessible(true);
        Student s = (Student) c.newInstance();
        f.set(s,3);
        int number = (int)f.get(s);
        System.out.println("修改之后的教师编号: "+ number);
    }

    public static void reflectPrivateMethod() throws NoSuchMethodException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class c = Class.forName("Student");
        Method m = c.getDeclaredMethod("function",String.class);
        System.out.println("获取私有方法名称: "+m.getName());
        m.setAccessible(true);
        Student s = (Student) c.newInstance();
        m.invoke(s,"被传入的参数");
    }
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        //create();
        //reflectConstructor();
        //reflectPrivateConstructor();
        //reflectPrivateField();
        reflectPrivateMethod();
    }
}
